<template>
  <div class="admin-container">
    <!-- 侧边栏 -->
    <el-aside :width="isSidebarCollapsed ? '64px' : '200px'" class="sidebar card">
      <el-menu
        :default-active="activeRoute"
        class="sidebar-menu"
        background-color="var(--sidebar-bg)"
        text-color="#fff"
        active-text-color="var(--accent-color)"
        :collapse="isSidebarCollapsed"
        router
        @select="handleMenuSelect"
      >
        <!-- 仪表盘菜单项 -->
        <el-menu-item v-if="visibleMenus.dashboard?.visible" index="/main/dashboard">
          <el-icon><House /></el-icon>
          <template #title>
            <span>仪表盘</span>
            <el-tag v-if="visibleMenus.dashboard?.readonly" type="info" size="small" class="readonly-tag">只读</el-tag>
          </template>
        </el-menu-item>
        
        <!-- 商品栏菜单项 -->
        <el-sub-menu v-if="visibleMenus.goods?.visible" index="/main/goods">
          <template #title>
            <el-icon><Goods /></el-icon>
            <span>商品栏</span>
          </template>
          <el-menu-item v-if="visibleMenus.goods?.children?.['goods-list']?.visible" index="/main/goods-list">
            <el-icon><List /></el-icon>
            商品列表
          </el-menu-item>
          <el-menu-item v-if="visibleMenus.goods?.children?.['goods-category']?.visible" index="/main/goods-category">
            <el-icon><Menu /></el-icon>
            商品分类
          </el-menu-item>
          <el-menu-item v-if="visibleMenus.goods?.children?.['product-spec']?.visible" index="/main/product-spec">
            <el-icon><SetUp /></el-icon>
            商品规格
          </el-menu-item>
          <el-menu-item v-if="visibleMenus.goods?.children?.['brand-management']?.visible" index="/main/brand-management">
            <el-icon><Star /></el-icon>
            品牌管理
          </el-menu-item>
        </el-sub-menu>
        
        <!-- 订单栏菜单项 -->
        <el-sub-menu v-if="visibleMenus.order?.visible" index="/main/order">
          <template #title>
            <el-icon><Document /></el-icon>
            <span>订单栏</span>
            <el-tag v-if="visibleMenus.order?.readonly" type="info" size="small" class="readonly-tag">只读</el-tag>
          </template>
          <el-menu-item v-if="visibleMenus.order?.children?.['order-list']?.visible" index="/main/order-list">
            <el-icon><List /></el-icon>
            订单列表
          </el-menu-item>
          <el-menu-item v-if="visibleMenus.order?.children?.['refund-handle']?.visible" index="/main/refund-handle">
            <el-icon><Back /></el-icon>
            退货退款处理
          </el-menu-item>
        </el-sub-menu>
        
        <!-- 权限栏菜单项 -->
        <el-sub-menu v-if="visibleMenus.permission?.visible" index="/main/permission">
          <template #title>
            <el-icon><User /></el-icon>
            <span>权限栏</span>
          </template>
          <el-menu-item v-if="visibleMenus.permission?.children?.['admin-list']?.visible" index="/main/admin-list">
            <el-icon><User /></el-icon>
            管理员列表
          </el-menu-item>
          <el-menu-item v-if="visibleMenus.permission?.children?.['user-list']?.visible" index="/main/user-list">
            <el-icon><User /></el-icon>
            用户列表
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    <!-- 主体内容 -->
    <el-container class="main-content card">
      <el-header class="header">
        <div class="header-left">
          <el-button @click="toggleSidebar" circle>
            <el-icon><Menu /></el-icon>
          </el-button>
          <span>乐淘后台管理系统</span>
        </div>
        <div class="header-right">
          <el-dropdown>
            <div class="user-info">
              <img src="@/assets/avatar.png" alt="用户头像" class="avatar" />
              <span class="username">{{ userStore.user?.username || '管理员' }}</span>
              <el-icon class="arrow-icon"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>个人中心</el-dropdown-item>
                <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-main class="main">
<!--        滚动容器        -->
        <div class="page-container">
          <div class="page-wrapper">
            <router-view />
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ArrowDown, House, Goods, List, Plus, Menu, SetUp, Star, Document, Back, Edit, User } from '@element-plus/icons-vue';
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store' // 导入 store

const route = useRoute();
const router = useRouter();
const userStore = useUserStore()

// 从 store 获取可见菜单配置
const visibleMenus = computed(() => userStore.getVisibleMenus)

// 记录当前激活的菜单
const activeRoute = ref('/main/dashboard')

const isSidebarCollapsed = ref(false);

const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value;
};

// 菜单选择处理（用于 router 模式）
const handleMenuSelect = (index) => {
  console.log('Menu selected:', index)
  router.push(index).catch(err => {
    console.error('Navigation failed:', err)
  })
}

// 监听路由变化，更新菜单激活状态
watch(() => route.path, (newPath) => {
  activeRoute.value = newPath
  console.log('Route changed to:', newPath)
}, { immediate: true })

// 退出登录的事件处理函数
const logout = () => {
  // 清除用户信息
  userStore.clearUserInfo()
  // 跳转到登录页
  router.push('/');
};

// 页面挂载时，恢复用户信息（页面刷新时恢复）
onMounted(() => {
  console.log('Main.vue mounted, current route:', route.path)
  if (!userStore.isLoggedIn) {
    const restored = userStore.restoreUserInfo()
    if (!restored) {
      console.warn('Failed to restore user info')
      router.push('/')
    }
  }
})

// 切换子页面自动滚动到顶部
import { onActivated } from 'vue'

onActivated(() => {
  document.querySelector('.page-container')?.scrollTo(0, 0)
})
</script>

<style scoped>
.admin-container {
  display: flex;
  height: 100vh;
}

.sidebar {
  background-color: var(--sidebar-bg, #2e3a4e); /* 使用CSS变量，fallback到默认 */
  color: #fff;
  transition: width 0.3s ease-in-out, background-color 0.3s;
}

.sidebar-menu {
  height: 100%;
  border-right: none;
}

.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  height: 48px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: var(--header-bg, #ffffff); /* 使用CSS变量 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  /* 新增：确保顶部栏高度合适，避免元素偏移 */
  height: 60px;
  transition: background-color 0.3s, box-shadow 0.3s; /* 添加过渡 */
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left span {
  margin-left: 10px;
  font-size: 18px;
  font-weight: bold;
  color: var(--text-color); /* 使用CSS变量 */
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  margin-right: 5px;
  color: var(--text-color); /* 使用CSS变量 */
}

.arrow-icon {
  font-size: 14px;
  color: var(--text-color); /* 使用CSS变量 */
}

.main {
  flex: 1;
  padding: 0px;
  background-color: var(--main-bg, #f5f7fa);
  overflow: hidden;
  transition: background-color 0.3s;
}

.page-container {
  height: 100%;
  width: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0;
  box-sizing: border-box;
}

.page-wrapper {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

/* 只读标签样式 */
.readonly-tag {
  margin-left: 8px;
}</style>